#include<opencv2/core.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2/imgproc.hpp>
using namespace cv;
#include<iostream>
#include<string>
#include <fstream>
using namespace std;
//输入图像
Mat img;
//灰度值归一化
Mat bgr;
//HSV图像
Mat hsv;
//色相
int hmin_low = 0;
const int hmin_low_Max = 180;
int hmax_low = 180;
const int hmax_low_Max = 180;

int hmin_high = 180;
const int hmin_high_Max = 180;
int hmax_high = 180;
const int hmax_high_Max = 180;
//饱和度
int smin = 0;
const int smin_Max = 255;
int smax = 255;
const int smax_Max = 255;
//亮度
int vmin = 106;
const int vmin_Max = 255;
int vmax = 255;
const int vmax_Max = 255;
//显示原图的窗口
string windowName = "src";
//输出图像的显示窗口
string dstName = "dst";
//输出图像
Mat dst;
//回调函数
void callBack(int, void*)
{
	//输出图像分配内存
	dst = Mat::zeros(img.size(), img.type());
	//掩码
	Mat mask = Mat::zeros(img.size(), CV_8UC1);
	// inRange(hsv, Scalar(hmin, smin, vmin), Scalar(hmax, smax, vmax), mask);
	for(int i = 0; i < hsv.rows;i++){
		for(int j = 0; j < hsv.cols; j++){
			if((((hsv.at<cv::Vec3b>(i,j)[0] >= hmin_low && hsv.at<cv::Vec3b>(i,j)[0] <= hmax_low) ||
					(hsv.at<cv::Vec3b>(i,j)[0] >= hmin_high && hsv.at<cv::Vec3b>(i,j)[0] <= hmax_high)) &&
					(hsv.at<cv::Vec3b>(i,j)[1] >= smin && hsv.at<cv::Vec3b>(i,j)[1] <= smax) &&
					(hsv.at<cv::Vec3b>(i,j)[2] >= vmin && hsv.at<cv::Vec3b>(i,j)[2] <= vmax))){
				mask.at<uchar>(i,j) = 255;
			}
			else{
				mask.at<uchar>(i,j) = 0;
			}
		}
	}
	//掩模到原图的转换
	for (int r = 0; r < bgr.rows; r++)
	{
		for (int c = 0; c < bgr.cols; c++)
		{
			if (mask.at<uchar>(r, c) == 255)
			{
				dst.at<Vec3b>(r, c) = bgr.at<Vec3b>(r, c);
			}
		}
	}
	//输出图像
	imshow(dstName, dst);
	imshow("mask",mask);
	//保存图像
	//dst.convertTo(dst, CV_8UC3, 255.0, 0);
	imwrite("result/HSV_inRange.jpg", dst);
}
int main(int argc, char** argv)
{
	// cv::VideoCapture cap("/home/xjturm/Downloads/3cut.avi");
	// cap >> img;
	//输入图像
	img = imread("/home/newsun/Pictures/Screenshot from 2021-12-08 03-35-46.png");
	if (!img.data || img.channels() != 3)
		return -1;
	imshow(windowName, img);
	bgr = img.clone();
	//颜色空间转换
	cvtColor(bgr, hsv, cv::COLOR_BGR2HSV);
	// cout << hsv << endl;
	//定义输出图像的显示窗口
	namedWindow(dstName, WINDOW_GUI_EXPANDED);
	//调节色相 H
	createTrackbar("hmin_low", dstName, &hmin_low, hmin_low_Max, callBack);
	createTrackbar("hmax_low", dstName, &hmax_low, hmax_low_Max, callBack);

	createTrackbar("hmin_high", dstName, &hmin_high, hmax_high_Max, callBack);
	createTrackbar("hmax_high", dstName, &hmax_high, hmax_high_Max, callBack);
	//调节饱和度 S
	createTrackbar("smin", dstName, &smin, smin_Max, callBack);
	createTrackbar("smax", dstName, &smax, smax_Max, callBack);
	//调节亮度 V
	createTrackbar("vmin", dstName, &vmin, vmin_Max, callBack);
	createTrackbar("vmax", dstName, &vmax, vmax_Max, callBack);
	callBack(0, 0);
	waitKey(0);
	ofstream output_hsv("result/out.txt");
	output_hsv << hmin_low << " " << hmax_low << " " << hmin_high << " " << hmax_high << " " << smin << " " << smax << " " << vmin << " " << vmax;
	return 0;
}